package com.sun.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.dto.TagAndAmount;
import com.sun.dto.TypeAndAmount;
import com.sun.pojo.Blog;
import com.sun.pojo.Comment;
import com.sun.pojo.Type;
import com.sun.service.BlogService;
import com.sun.service.CommentService;
import com.sun.service.TagService;
import com.sun.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author: glorysun
 * @date: 2020/8/3
 */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/about")
    public String about(Model model){
        model.addAttribute("types", typeService.selectTypeList());
        model.addAttribute("tags", tagService.selectTagList());
        return "about";
    }

    @GetMapping("/")
    public String index(Model model,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        //博客展示
        PageHelper.startPage(pageNum, 5);
        List<Blog> allBlog = blogService.selectBlogList();
        PageInfo<Blog> pageInfo = new PageInfo<>(allBlog);
        model.addAttribute("pageInfo", pageInfo);
        //分类展示
        model.addAttribute("types",typeService.selectTypeAndAmount());
        //标签展示
        model.addAttribute("tags",tagService.selectTagAndAmount());
        //最新博客
        model.addAttribute("newBlog",blogService.selectBlogListTen());
        return "index";
    }

    @GetMapping("/blog/{id}")
    public String blogDetails(@PathVariable("id") Long id,Model model){
        Blog blog=blogService.selectBlogByIdAndMarkdownTOHTML(id);
        List<Comment> comments=commentService.selectCommentByBlogId(id);
        model.addAttribute("comments",comments);
        model.addAttribute("blog",blog);
        return "blog";
    }

    //查询博客
    @GetMapping("/search")
    public String search(String query,Model model,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum, 5);
        List<Blog> allBlog = blogService.selectBlogByTitle(query);
        PageInfo<Blog> pageInfo = new PageInfo<>(allBlog);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query",query);
        return "search";
    }



}
